var PhysicsHelper = Packages.JET.physics.PhysicsHelper,
    Vec2d = Packages.JET.geom.Vec2d,
    KeyHelper = Packages.JET.VirtualKeyboard.KeyHelper,
    KeyEvent = java.awt.event.KeyEvent;

Scene.damping = .995;

var sb = Scene.getSpringBodyList().get(36),
    masses = sb.getMassList(),
    springs = sb.getSpringList();

var keyUp = CC.getVKeyboard().getKey(KeyEvent.VK_UP),
    keyDown = CC.getVKeyboard().getKey(KeyEvent.VK_DOWN),
    keyLeft = CC.getVKeyboard().getKey(KeyEvent.VK_LEFT),
    keyRight = CC.getVKeyboard().getKey(KeyEvent.VK_RIGHT),
    keyShift = CC.getVKeyboard().getKey(KeyEvent.VK_SHIFT),
    keyQ = CC.getVKeyboard().getKey(KeyEvent.VK_Q),
    keyA = CC.getVKeyboard().getKey(KeyEvent.VK_A),
    keyZ = CC.getVKeyboard().getKey(KeyEvent.VK_Z);

var mfl = masses.get(5),
    mfr = masses.get(6),
    mrl = masses.get(8),
    mrr = masses.get(7),
    mD  = masses.get(4);    // mass of direction

    var speed,
        speedMin = 0.,
        speedMax = 25,
        angleMax = Math.PI/3,
        angleMin = -angleMax;

    var kDrift = 2.5;
    var angle = 0.;

    function applyWheelFriction(_mass, _ortho, _kDrift) {
        var dot = _mass.getVelocity().getScalarProduct(_ortho);
        var k = -dot * _kDrift;
        var cor = _ortho.getScaled(k);
        _mass.getForce().add(cor);
    }

////////////////////////////////////////////////////////////////////////////////
//                        M A I N   L O O P   C O D E                         //
////////////////////////////////////////////////////////////////////////////////

    // Zero Stuff
    var s = 0;
    //angle = 0;

    // Find current ride direction and its perpendicular
    var n = springs.get(31).getVector().getScaled(-1).getNormalized(),
        o = n.getOrthogonal();

    // Key events
    if (keyQ.isPressed()) {
        kDrift += 0.1;
    }
    if (keyA.isPressed()) {
        kDrift -= 0.1;
    }
    if (keyZ.isPressed()) {
        keyZ.setPressed(false);
        CC.GUIC.appendToOutput("kDrift: "+kDrift);
    }

    // Rear wheels
    if (keyShift.isPressed()) kDrift = .3;
    else kDrift = 2;

    applyWheelFriction(mrl, o, kDrift);
    applyWheelFriction(mrr, o, kDrift);

    // Front wheels
    var steerAngle = Math.PI/2.5;
    
    if (keyUp.isPressed()) s += speedMax;
    if (keyDown.isPressed()) s += -speedMax;

    if (keyLeft.isPressed()) angle +=  0.01;
    if (keyRight.isPressed()) angle -= 0.01;

    if (angle<angleMin)         angle = angleMin;
    else if (angle>angleMax)    angle = angleMax;

    if (angle<0) angle += 0.006;
    if (angle>0) angle -= 0.006;

    var ortho = o.getRotated(angle);
    
    var steerDir = n.getScaled(s).getRotated(angle);
    mfl.getForce().add(steerDir);
    mfr.getForce().add(steerDir);

    applyWheelFriction(mfl, ortho, 1);
    applyWheelFriction(mfr, ortho, 1);

    //mD.getPosition().become(mfr.getPosition().getAdded(springs.get(0).getVector().getScaled(.5)).getAdded(steerDir));


